#include <iostream>
#include <string.h>
using namespace std;
const int inf=0x7fffffff;


int main(){
	int ans=0;
	int n;
	cin>>n;
	int a[n];
	for(int i=0;i<n;i++)
		cin>>a[i];
	int sum[n];
	int q[n];
	memset(q,-1,sizeof(q));
	q[0] = a[0];
	sum[0] = a[0];
	for(int i=1;i<n;i++){
		if(q[i-1] < a[i]){
			ans += sum[i-1];
			q[i] = a[i];
			sum[i] = sum[i-1]+a[i];
			continue;
		}
		q[i] = inf;
		int l=0,r=i;
		while(r-l > 1){
			int mid=(l+r)/2;
			if(q[mid] >= a[i])
				r = mid;
			else
				l = mid;
		}
		if(l == r)
			r++;
		if(q[l] >= a[i])
			l--,r--;
		if(l >= 0)
			ans += sum[l];
		memcpy(q+r+1,q+r,(i-l)*sizeof(int));
		memcpy(sum+r+1,sum+r,(i-l)*sizeof(int));
		q[r] = a[i];
		if(l >= 0)
			sum[r] = sum[l]+a[i];
		else
			sum[0] = a[i];
		for(int j=r+1;j<=i;j++){
			sum[j] += a[i];
		}
	}
	
//	for(int i=0;i<n;i++)
//		cout<<q[i]<<" ";
//	cout<<endl;
//	for(int i=0;i<n;i++)
//		cout<<sum[i]<<" ";
//	cout<<endl;
	
	cout<<ans;
	return 0;
}
